// 内存
<template>
  <div>
    <!-- 内存利用率 -->
    <div class="bg-fff pAll mb_10 contentList">
      <div class="header">
        <span>内存利用率</span>
        <ul>
          <li>最新值：{{ list1.utilization.last }} %</li>
          <li>最小值：{{ list1.utilization.min }} %</li>
          <li>平均值：{{ list1.utilization.avg }} %</li>
          <li>最大值：{{ list1.utilization.max }} %</li>
        </ul>
      </div>
      <div style="height: 300px">
        <echarts-load v-if="memoryFlag1 || reload_memory1" :chartFlag="memoryFlag1" :reload="reload_memory1" @refreshF="refreshDl1" />
        <cpu-line v-else :chartsData="echartData_memory1" />
      </div>
    </div>
    <!-- 内存空间 -->
    <div class="bg-fff pAll mb_10 contentList">
      <div class="header">
        <span>内存空间</span>
      </div>
      <div style="height: 395px">
        <echarts-load v-if="memoryFlag2 || reload_memory2" :chartFlag="memoryFlag2" :reload="reload_memory2" @refreshF="refreshDl2" />
        <div v-else>
          <el-row class="toggleList">
            <el-col :span="12">
              <div class="toggleItem">
                <h2>总内存（total memory）</h2>
                <el-row class="item_param">
                  <el-col :span="12">
                    <div>
                      <p>最新值：{{ list2.totalMemory.last }}</p>
                      <p>平均值：{{ list2.totalMemory.avg }}</p>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div>
                      <p>最小值：{{ list2.totalMemory.min }}</p>
                      <p>最大值：{{ list2.totalMemory.max }}</p>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="toggleItem">
                <h2>可用内存（available memory）</h2>
                <el-row class="item_param">
                  <el-col :span="12">
                    <div>
                      <p>最新值：{{ list2.availableSpace.last }}</p>
                      <p>平均值：{{ list2.availableSpace.avg }}</p>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div>
                      <p>最小值：{{ list2.availableSpace.min }}</p>
                      <p>最大值：{{ list2.availableSpace.max }}</p>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-col>
          </el-row>
          <div>
            <!-- <echarts-load v-if="memoryFlag2 || reload_memory2" :chartFlag="memoryFlag2" :reload="reload_memory2" @refreshF="refreshDl2" />
            <cpu-line v-else :chartsData="echartData_memory2" /> -->
            <cpu-line :chartsData="echartData_memory2" />
          </div>
        </div>
      </div>
    </div>
    <!-- 内存交换使用 -->
    <div class="bg-fff pAll mb_10 contentList">
      <div class="header">
        <span>内存交换使用</span>
      </div>
      <div style="height: 395px">
        <echarts-load v-if="memoryFlag3 || reload_memory3" :chartFlag="memoryFlag3" :reload="reload_memory3" @refreshF="refreshDl3" />
        <div v-else>
          <el-row class="toggleList">
            <el-col :span="12">
              <div class="toggleItem">
                <h2>总交换空间（total swap space）</h2>
                <el-row class="item_param">
                  <el-col :span="12">
                    <div>
                      <p>最新值：{{ list3.totalSwapSpace.last | threeNum }}</p>
                      <p>平均值：{{ list3.totalSwapSpace.avg | threeNum }}</p>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div>
                      <p>最小值：{{ list3.totalSwapSpace.min | threeNum }}</p>
                      <p>最大值：{{ list3.totalSwapSpace.max | threeNum }}</p>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="toggleItem">
                <h2>可用交换空间（free swap space）</h2>
                <el-row class="item_param">
                  <el-col :span="12">
                    <div>
                      <p>最新值：{{ list3.freeSwapSpace.last | threeNum }}</p>
                      <p>平均值：{{ list3.freeSwapSpace.avg | threeNum }}</p>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div>
                      <p>最小值：{{ list3.freeSwapSpace.min | threeNum }}</p>
                      <p>最大值：{{ list3.freeSwapSpace.max | threeNum }}</p>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-col>
          </el-row>
          <div>
            <!-- <echarts-load v-if="memoryFlag3 || reload_memory3" :chartFlag="memoryFlag3" :reload="reload_memory3" @refreshF="refreshDl3" />
        <cpu-line v-else :chartsData="echartData_memory3" /> -->
            <cpu-line :chartsData="echartData_memory3" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { timeLoad } from '@/assets/js/setTime'
import cpuLine from '@/components/Echarts/cloudEcharts/cpuLine'
import echartsLoad from '@/components/Echarts/echartsLoad'
export default {
  data() {
    return {
      searchCondition: {},
      memoryFlag1: false,
      reload_memory1: false,
      memoryTime1: null,
      echartData_memory1: {},
      memoryFlag2: false,
      reload_memory2: false,
      memoryTime2: null,
      echartData_memory2: {},
      memoryFlag3: false,
      reload_memory3: false,
      memoryTime3: null,
      echartData_memory3: {},
      list1: {
        utilization: { min: '', avg: '', last: '', max: '' },
      },
      list2: {
        totalMemory: { min: '', avg: '', last: '', max: '' }, // 内存总空间
        availableSpace: { min: '', avg: '', last: '', max: '' }, // 内存可用空间
      },
      list3: {
        totalSwapSpace: { min: '', avg: '', last: '', max: '' }, //  总交换空间
        freeSwapSpace: { min: '', avg: '', last: '', max: '' }, // 可用交换空间
      },
      initInterval: null,
    }
  },
  components: { cpuLine, echartsLoad },
  props: ['childData'],
  watch: {
    childData: {
      deep: true,
      handler(newVal, oldVal) {
        this.searchCondition = newVal
        this.initList_findUtilization() // 内存利用率
        this.initList_findSpace() // 内存使用率
        this.initList_findSwap() // 内存交换使用
        if (newVal.type === 'change') {
          clearInterval(this.initInterval)
        }
      },
    },
    memoryFlag1(newVal, oldVal) {
      this.memoryTime1 = setTimeout(() => {
        if (this.memoryFlag1) {
          this.memoryFlag1 = false
          this.reload_memory1 = true
        }
      }, timeLoad)
    },
    memoryFlag2(newVal, oldVal) {
      this.memoryTime2 = setTimeout(() => {
        if (this.memoryFlag2) {
          this.memoryFlag2 = false
          this.reload_memory2 = true
        }
      }, timeLoad)
    },
    memoryFlag3(newVal, oldVal) {
      this.memoryTime3 = setTimeout(() => {
        if (this.memoryFlag3) {
          this.memoryFlag3 = false
          this.reload_memory3 = true
        }
      }, timeLoad)
    },
  },
  created() {
    this.searchCondition = this.childData
    this.initList_findUtilization() // 内存利用率
    this.initList_findSpace() // 内存使用率
    this.initList_findSwap() // 内存交换使用
    if (this.searchCondition.type !== 'change') {
      this.initInterval = setInterval(() => {
        this.getSearchTime()
        this.initList_findUtilization() // 内存利用率
        this.initList_findSpace() // 内存使用率
        this.initList_findSwap() // 内存交换使用
      }, 1000 * 30)
    }
  },
  methods: {
    // 获取时间
    getSearchTime() {
      var difference = new Date(this.searchCondition.endDate).getTime() - new Date(this.searchCondition.startDate).getTime()
      var startDate = this.initTime(new Date(new Date().getTime() - difference))
      var endDate = this.initTime(new Date())
      // console.log(startDate, '----', endDate)
      this.childValue = {
        startDate: startDate, // 开始日期、(yyyy-MM-dd HH:mm:ss)
        endDate: endDate, // 结束日期、(yyyy-MM-dd HH:mm:ss)
        type: '',
      }
      this.$emit('childByValue', this.childValue)
    },
    initTime(date) {
      const Y = date.getFullYear()
      const M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var h = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours()
      var m = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes()
      var s = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds()
      return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s // yyyy-MM-dd HH:mm:ss
    },
    // 内存利用率
    async initList_findUtilization() {
      clearTimeout(this.memoryTime1)
      this.memoryFlag1 = true
      this.reload_memory1 = false
      const params = new URLSearchParams()
      params.append('relSerialNo', this.$route.query.relSerialNo) // 主机流水号
      params.append('startDate', this.searchCondition.startDate) // 开始日期、(yyyy-MM-dd HH:mm:ss)
      params.append('endDate', this.searchCondition.endDate) // 结束日期、(yyyy-MM-dd HH:mm:ss)
      const { data: res } = await this.$http.post('snmp/memLog/findUtilization', params)
      this.memoryFlag1 = false
      // this.reload_memory1 = true
      this.reload_memory1 = false
      // console.log(res)
      switch (res.code) {
        case '0000':
          var details_arr = res.data.details
          var details_utilization = details_arr.utilization
          for (var k in details_utilization) {
            details_utilization[k] = details_utilization[k].toFixed(2)
          }
          // this.list1 = res.data.details
          this.list1 = details_arr
          var xData = []
          var timeList = {
            utilization: [],
          }
          var list = {
            utilization: '内存利用率（memory utilization）',
          }
          res.data.list.forEach((item, index) => {
            var time = new Date(item.createDate)
            xData.push(this.getTime(time))
            timeList.utilization.push(item.utilization.toFixed(2))
          })
          var seriesDate = []
          for (const k in list) {
            seriesDate.push({
              name: list[k],
              type: 'line',
              // stack: '总量',
              data: timeList[k],
            })
          }
          this.echartData_memory1 = {
            id: 'memory_line1',
            type: 'green',
            xData: xData,
            legendData: ['内存利用率（memory utilization）'],
            seriesDate: seriesDate,
            unit: ' %',
          }
          break
        default:
          this.echartData_memory1 = {
            id: 'memory_line1',
            type: 'green',
            xData: [],
            legendData: [],
            seriesDate: [],
            unit: ' %',
          }
          this.memoryFlag1 = false
          this.reload_memory1 = true
          break
      }
    },
    refreshDl1() {
      this.reload_memory1 = false
      this.initList_findUtilization()
    },
    // 内存使用率
    async initList_findSpace() {
      clearTimeout(this.memoryTime1)
      this.memoryFlag2 = true
      this.reload_memory2 = false
      const params = new URLSearchParams()
      params.append('relSerialNo', this.$route.query.relSerialNo) // 主机流水号
      params.append('startDate', this.searchCondition.startDate) // 开始日期、(yyyy-MM-dd HH:mm:ss)
      params.append('endDate', this.searchCondition.endDate) // 结束日期、(yyyy-MM-dd HH:mm:ss)
      const { data: res } = await this.$http.post('snmp/memLog/findSpace', params)
      this.memoryFlag2 = false
      // this.reload_memory2 = true
      this.reload_memory2 = false
      switch (res.code) {
        case '0000':
          var totalMemory = res.data.details.totalMemory // 总内存
          var availableSpace = res.data.details.availableSpace // 内存可用空间
          // var availableSpace = {}
          res.data.list.forEach((item, index) => {
            if (item.type) {
              if (res.data.list[0].type === 'kb') {
                this.getList2('KB', availableSpace, totalMemory)
              } else if (res.data.list[0].type === 'b') {
                this.getList2('B', availableSpace, totalMemory)
              }
              return true
            }
          })
          // this.list2 = res.data.details
          var xData = []
          var timeList = {
            totalMemory: [], // 总内存
            availableSpace: [], // 内存可用空间
          }
          var list = {
            totalMemory: '总内存（total memory）',
            availableSpace: '可用内存（available memory）',
          }
          res.data.list.forEach((item, index) => {
            var time = new Date(item.createDate)
            xData.push(this.getTime(time))
            var type = item.type
            // console.log(res.data.list[0].type)
            var xx = 0
            var yy = 0
            if (item.availableSpace > 0 || item.totalMemory > 0) {
              if (type === 'kb') {
                // timeList.availableSpace.push(this.formatKBytes_no(item.availableSpace)) // 可用内存
                // timeList.totalMemory.push(this.formatKBytes_no(item.totalMemory)) // 总内存
                xx = this.formatKBytes_no(item.availableSpace)
                yy = this.formatKBytes_no(item.totalMemory)
              } else if (type === 'b') {
                // console.log(this.formatKBytes_no(item.totalMemory))
                // timeList.availableSpace.push(this.formatBytes_no(item.availableSpace)) // 可用内存
                // timeList.totalMemory.push(this.formatBytes_no(item.totalMemory)) // 总内存
                xx = this.formatBytes_no(item.availableSpace)
                yy = this.formatBytes_no(item.totalMemory)
              }
            } else {
              xx = item.availableSpace
              yy = item.totalMemory
            }

            timeList.availableSpace.push(xx)
            timeList.totalMemory.push(yy)
          })
          var seriesDate = []
          for (const k in list) {
            seriesDate.push({
              name: list[k],
              type: 'line',
              // stack: '总量',
              data: timeList[k],
            })
          }
          this.echartData_memory2 = {
            id: 'memory_line2',
            type: 'green',
            xData: xData,
            legendData: ['总内存（total memory）', '可用内存（available memory）'],
            seriesDate: seriesDate, // x轴
            unit: ' GB',
          }
          // console.log(this.echartData_memory2)
          break
        default:
          this.echartData_memory2 = {
            id: 'memory_line2',
            type: 'green',
            xData: [],
            legendData: [],
            seriesDate: [],
            unit: ' GB',
          }
          this.memoryFlag2 = false
          this.reload_memory2 = true
          break
      }
    },
    refreshDl2() {
      this.reload_memory2 = false
      this.initList_findSpace()
    },
    // 内存交换使用
    async initList_findSwap() {
      clearTimeout(this.memoryTime1)
      this.memoryFlag3 = true
      this.reload_memory3 = false
      const params = new URLSearchParams()
      params.append('relSerialNo', this.$route.query.relSerialNo) // 主机流水号
      params.append('startDate', this.searchCondition.startDate) // 开始日期、(yyyy-MM-dd HH:mm:ss)
      params.append('endDate', this.searchCondition.endDate) // 结束日期、(yyyy-MM-dd HH:mm:ss)
      const { data: res } = await this.$http.post('snmp/memLog/findSwap', params)
      this.memoryFlag3 = false
      // this.reload_memory3 = true
      this.reload_memory3 = false
      switch (res.code) {
        case '0000':
          // this.list3 = res.data.details
          var totalSwapSpace = res.data.details.totalSwapSpace
          var freeSwapSpace = res.data.details.freeSwapSpace
          this.getList3('KB', totalSwapSpace, freeSwapSpace)
          var xData = []
          var timeList = {
            totalSwapSpace: [],
            freeSwapSpace: [],
          }
          var list = {
            totalSwapSpace: '总交换空间（total swap space）',
            freeSwapSpace: '可用交换空间（free swap space）',
          }
          res.data.list.forEach((item, index) => {
            var time = new Date(item.createDate)
            xData.push(this.getTime(time))
            timeList.totalSwapSpace.push(this.formatKBytes_no(item.totalSwapSpace)) // 总交换空间
            timeList.freeSwapSpace.push(this.formatKBytes_no(item.freeSwapSpace)) // 可用交换空间
          })
          var seriesDate = []
          for (const k in list) {
            seriesDate.push({
              name: list[k],
              type: 'line',
              // stack: '总量',
              data: timeList[k],
            })
          }
          this.echartData_memory3 = {
            id: 'memory_line3',
            type: 'green',
            xData: xData,
            legendData: ['总交换空间（total swap space）', '可用交换空间（free swap space）'],
            seriesDate: seriesDate,
            unit: ' GB',
          }
          break
        default:
          this.echartData_memory3 = {
            id: 'memory_line3',
            type: 'green',
            xData: [],
            legendData: [],
            seriesDate: [],
            unit: ' GB',
          }
          this.memoryFlag3 = false
          this.reload_memory3 = true
          break
      }
    },
    refreshDl3() {
      this.reload_memory3 = false
      this.initList_findSwap()
    },
    // 格式化时间
    getTime(date) {
      const Y = date.getFullYear()
      const M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var h = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours()
      var m = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes()
      var s = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds()
      return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s // yyyy-MM-dd HH:mm:ss
    },
    formatBytes(bytes) {
      if (bytes < 1024) return bytes + ' Bytes'
      else if (bytes < 1048576) return (bytes / 1024).toFixed(2) + ' KB'
      else if (bytes < 1073741824) return (bytes / 1048576).toFixed(2) + ' MB'
      else return (bytes / 1073741824).toFixed(2) + ' GB'
    },
    formatKBytes(kbytes) {
      if (kbytes < 1024) return kbytes + ' KB'
      else if (kbytes < 1048576) return (kbytes / 1024).toFixed(2) + ' MB'
      else if (kbytes < 1073741824) return (kbytes / 1048576).toFixed(2) + ' GB'
      else return (kbytes / 1073741824).toFixed(2) + ' TB'
    },
    formatKBytes_no(kbytes) {
      return (kbytes / 1024 / 1024).toFixed(2)
    },
    formatBytes_no(bytes) {
      return (bytes / 1024 / 1024 / 1024).toFixed(2)
    },
    getList2(val, availableSpace, totalMemory) {
      for (var k in availableSpace) {
        this.list2.availableSpace[k] = this[`format${val}ytes`](availableSpace[k])
      }
      for (var j in totalMemory) {
        this.list2.totalMemory[j] = this[`format${val}ytes`](totalMemory[j])
      }
    },
    getList3(val, totalSwapSpace, freeSwapSpace) {
      for (var k in totalSwapSpace) {
        this.list3.totalSwapSpace[k] = this[`format${val}ytes`](totalSwapSpace[k])
      }
      for (var j in freeSwapSpace) {
        this.list3.freeSwapSpace[j] = this[`format${val}ytes`](freeSwapSpace[j])
      }
    },
  },
  destroyed() {
    clearInterval(this.initInterval)
  },
}
</script>
<style lang="scss" scoped>
@import '@/assets/scss/cloudDetails.scss';
</style>
